package com.maint.m

import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.activity.viewModels
import com.maint.m.TokenManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.maint.m.data.GlobalData
import com.maint.m.data.model.TicketItem
import com.maint.m.utils.BuildConfig
import com.maint.m.viewmodel.TicketListViewModel
import okio.ByteString
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import okio.BufferedSink
import okio.Okio


import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.util.concurrent.TimeUnit
import org.json.JSONObject


class TicketListActivity : BaseActivity() {

    private val viewModel: TicketListViewModel by viewModels()
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout
    private lateinit var adapter: TicketListAdapter
    private lateinit var linearLayoutManager: LinearLayoutManager
    
    private lateinit var fabAdd: com.google.android.material.floatingactionbutton.FloatingActionButton

    private var isTicketListVisible = false
    
    // 相机相关变量
    private var currentPhotoPath: String? = null
    private val REQUEST_CAMERA_PERMISSION = 100
    
    // 用于处理相机结果的启动器
    private lateinit var cameraResultLauncher: ActivityResultLauncher<Intent>
    
    // 加载对话框
    private var loadingDialog: ProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 设置标题栏文字
        setToolbarTitle("待办")


        // 初始化相机结果启动器
        initCameraResultLauncher()
        
        // 初始化添加按钮
        initAddButton()
        
        initViews()
        setupRecyclerView()
        setupRefresh()
        observeViewModel()
        
        // 初始加载数据
        viewModel.loadData(1)
    }
    
    // 显示加载对话框
    private fun showLoadingDialog() {
        try {
            // 如果对话框已存在，则先关闭
            if (loadingDialog != null && loadingDialog?.isShowing == true) {
                loadingDialog?.dismiss()
            }
            
            // 创建新的进度对话框
            loadingDialog = ProgressDialog(this)
            loadingDialog?.setTitle("处理中")
            loadingDialog?.setMessage("操作票识别中...")
            loadingDialog?.setCancelable(false) // 不可取消
            loadingDialog?.setCanceledOnTouchOutside(false) // 点击外部不可取消
            
            // 显示对话框
            loadingDialog?.show()
        } catch (e: Exception) {
            Log.e(TAG, "显示加载对话框失败: ${e.message}", e)
        }
    }
    
    // 关闭加载对话框
    private fun dismissLoadingDialog() {
        try {
            runOnUiThread {
                if (loadingDialog != null && loadingDialog?.isShowing == true) {
                    loadingDialog?.dismiss()
                    loadingDialog = null
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "关闭加载对话框失败: ${e.message}", e)
        }
    }
    

    
    companion object {
        private const val TAG = "TicketListActivity"
        const val NEED_REFRESH = "NEED_REFRESH"
    }

    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerView)
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)

        adapter = TicketListAdapter {
    ticketItem: com.maint.m.TicketItem, position ->
            // 使用完整包名的TicketItem类型
            handleItemClick(ticketItem, position)
        }
    }
    
    // 初始化相机结果启动器
    private fun initCameraResultLauncher() {
        try {
            cameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                try {
                    if (result.resultCode == RESULT_OK) {
                        // 拍照成功，上传图片
                        if (!currentPhotoPath.isNullOrEmpty()) {
                            // 显示上传中提示
                            Toast.makeText(this, "正在上传图片...", Toast.LENGTH_SHORT).show()
                            
                            // 延迟显示加载对话框，让上传提示先显示一会儿
                            Thread.sleep(2000)
                            
                            // 在UI线程显示加载对话框
                            runOnUiThread {
                                showLoadingDialog()
                            }
                            
                            uploadImageToServer(currentPhotoPath!!)
                        }
                    }
                } catch (e: Exception) {
                    // 发生异常时关闭加载对话框
                    runOnUiThread {
                        dismissLoadingDialog()
                    }
                    Log.e(TAG, "相机结果处理异常: ${e.message}", e)
                    Toast.makeText(this, "处理相机结果失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "初始化相机结果启动器失败: ${e.message}", e)
        }
    }

    // 初始化添加按钮
    private fun initAddButton() {
        try {
            // 添加按钮（实现推流功能）
            fabAdd = findViewById(R.id.fab_add)
            fabAdd.setOnClickListener {
                // 创建选择对话框
                val options = arrayOf("拍照识别", "视觉识别")
                AlertDialog.Builder(this)
                    .setTitle("选择识别方式")
                    .setItems(options) { dialog, which ->
                        when (which) {
                            0 -> {
                                // 拍照识别：直接打开相机拍照并上传
                                if (checkCameraPermission()) {
                                    dispatchTakePictureForUpload()
                                } else {
                                    requestCameraPermission()
                                }
                            }
                            1 -> {
                                // 视觉识别：跳转到StreamingActivity
                                val intent = Intent(this@TicketListActivity, StreamingActivity::class.java)
                                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                                startActivity(intent)
                            }
                        }
                        dialog.dismiss()
                    }
                    .show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "初始化添加按钮失败: ${e.message}", e)
        }
    }

    private fun observeViewModel() {
        viewModel.ticketList.observe(this) {
            // 直接使用返回的列表，通过适配器内部处理类型转换
            adapter.setItems(it)
        }

        viewModel.isRefreshing.observe(this) {
            swipeRefreshLayout.isRefreshing = it
        }

        viewModel.errorMessage.observe(this) {
            it?.let { errorMsg ->
                Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show()
                Log.e("TicketListActivity", errorMsg)
            }
        }
    }

    private fun handleItemClick(ticketItem: com.maint.m.TicketItem, position: Int) {
        // 跳转到详情页
        val intent = Intent(this@TicketListActivity, TicketDetailActivity::class.java)
        intent.putExtra("ticket_item", ticketItem)
        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        startActivity(intent)
    }

    // 检查相机权限
    private fun checkCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            android.Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }

    // 请求相机权限
    private fun requestCameraPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(android.Manifest.permission.CAMERA),
            REQUEST_CAMERA_PERMISSION
        )
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，执行拍照
                dispatchTakePictureForUpload()
            } else {
                Toast.makeText(this, "相机权限被拒绝，无法拍照", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 创建临时图片文件
    @Throws(IOException::class)
    private fun createImageFile(): File {
        // 创建时间戳文件名
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        
        // 获取存储目录
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        
        // 检查存储目录是否为null
        if (storageDir == null) {
            Log.e("Upload", "无法获取存储目录: Environment.DIRECTORY_PICTURES")
            throw IOException("无法获取存储目录")
        }
        
        Log.i("Upload", "尝试使用存储目录: ${storageDir.absolutePath}")
        
        // 确保目录存在，如果不存在则创建
        if (!storageDir.exists()) {
            Log.i("Upload", "目录不存在，正在创建: ${storageDir.absolutePath}")
            // 使用mkdirs()创建所有必要的父目录
            val created = storageDir.mkdirs()
            Log.i("Upload", "目录创建结果: $created")
            
            // 再次检查目录是否存在
            if (!storageDir.exists()) {
                Log.e("Upload", "创建目录失败，目录仍然不存在: ${storageDir.absolutePath}")
                throw IOException("无法创建存储目录: ${storageDir.absolutePath}")
            } else {
                Log.i("Upload", "目录创建成功: ${storageDir.absolutePath}")
            }
        } else {
            Log.i("Upload", "目录已存在: ${storageDir.absolutePath}")
        }
        
        try {
            // 创建临时文件
            val imageFile = File.createTempFile(
                "JPEG_${timeStamp}_", /* 前缀 */
                ".jpg", /* 后缀 */
                storageDir /* 目录 */
            )
            
            // 保存文件路径以便后续使用
            currentPhotoPath = imageFile.absolutePath
            Log.i("Upload", "成功创建临时图片文件: ${imageFile.absolutePath}")
            
            return imageFile
        } catch (e: IOException) {
            Log.e("Upload", "创建临时文件失败: ${e.message}", e)
            // 如果创建临时文件失败，尝试直接创建文件
            val directFilePath = File(storageDir, "JPEG_${timeStamp}_direct.jpg")
            if (directFilePath.createNewFile()) {
                currentPhotoPath = directFilePath.absolutePath
                Log.i("Upload", "使用备用方式成功创建图片文件: ${directFilePath.absolutePath}")
                return directFilePath
            }
            throw IOException("无法创建临时图片文件", e)
        }
    }

    // 启动相机进行拍照
    private fun dispatchTakePictureForUpload() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // 确保有相机应用程序可以处理意图
            takePictureIntent.resolveActivity(packageManager)?.also {
                // 创建文件以保存图像
                val photoFile: File? = try {
                    createImageFile()
                } catch (ex: IOException) {
                    // 错误处理
                    Log.e("ImageCapture", "创建图片文件失败: ${ex.message}")
                    null
                }
                // 继续只有在文件创建成功时
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                        this,
                        "com.maint.m.fileprovider",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    cameraResultLauncher.launch(takePictureIntent)
                }
            }
        }
    }

    // 上传图片到服务器
    private fun uploadImageToServer(filePath: String) {
        // 生成唯一请求ID，用于追踪重复调用
        val randomStr = (Math.random() * 1000000).toLong().toString(36).padEnd(6, '0')
        val requestId = "REQ_${System.currentTimeMillis()}_${randomStr.substring(0, 6)}"
        
        // 开始上传图片
        Log.i("Upload", "[$requestId] 开始上传图片，文件路径: $filePath")
        
        // 创建一个新线程进行网络请求，避免阻塞UI线程
        Thread {
            var responseBody: String? = null
            var responseCode: Int? = null
            var responseMessage: String? = null
            var errorMessage: String? = null
            
            try {
                val file = File(filePath)
                
                // 检查文件是否存在且可读
                if (!file.exists() || !file.canRead() || file.length() <= 0L) {
                    errorMessage = "文件不存在或无法读取: $filePath, 大小: ${file.length()}"
                    Log.e("Upload", "[$requestId] $errorMessage")
                    return@Thread
                }
                
                // 使用OkHttpClient实现上传，添加超时设置
                val client = OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)    // 连接超时
                    .readTimeout(60, TimeUnit.SECONDS)       // 读取超时
                    .writeTimeout(30, TimeUnit.SECONDS)      // 写入超时
                    .build()
                
                // 构建MultipartBody，使用文件名而不是完整路径
                val fileName = File(filePath).name
                Log.i("Upload", "[$requestId] 使用文件名: $fileName 进行上传")
                
                val body = MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", fileName, 
                        file.asRequestBody("application/octet-stream".toMediaType()))
                    .build()
                
                // 构建请求，使用完整URL
                val request = Request.Builder()
                    .url(BuildConfig.APP_BASE_URL + "/api/v1/services/aigc/multimodal-generation/generation")
                    .post(body)
                    .addHeader("token", "zMsWxVfGhCweq0lmZDiN4pavF")
                    .build()
                
                Log.i("Upload", "[$requestId] 请求已构建完成，开始发送请求")
                
                // 执行同步请求
                val response = client.newCall(request).execute()
                responseCode = response.code
                responseMessage = response.message
                
                if (response.isSuccessful) {
                    responseBody = response.body?.string() ?: "无响应内容"
                    Log.i("Upload", "[$requestId] 上传成功，响应: $responseBody")
                    
                    // 上传成功后清理临时文件，避免占用存储空间
                    try {
                        if (file.exists() && file.delete()) {
                            Log.i("Upload", "[$requestId] 临时图片文件已删除")
                        }
                    } catch (e: Exception) {
                        Log.w("Upload", "[$requestId] 删除临时文件失败: ${e.message}")
                    }
                } else {
                    errorMessage = "图片上传失败: $responseCode $responseMessage"
                    Log.e("Upload", "[$requestId] $errorMessage")
                }
            } catch (e: Exception) {
                errorMessage = "上传异常: ${e.message}"
                Log.e("Upload", "[$requestId] 上传异常", e)
            } finally {
                // 所有操作完成后，在UI线程统一处理结果
                runOnUiThread {
                    if (errorMessage != null) {
                        // 发生错误时关闭加载对话框
                        dismissLoadingDialog()
                        Toast.makeText(this@TicketListActivity, errorMessage, Toast.LENGTH_SHORT).show()
                    } else if (responseBody != null) {
                        try {
                            // 解析JSON响应
                            val jsonObject = JSONObject(responseBody)
                            val statusCode = jsonObject.optString("statusCode")
                            val resultObject = jsonObject.optJSONObject("result")
                            Log.i("Upload", "[$requestId] 响应状态码: $statusCode")
                            Log.i("Upload", "[$requestId] 响应数据: ${resultObject?.toString()}")

                            // 检查状态码是否为200
                            if (statusCode == "200") {
                                Log.i("Upload", "[$requestId] 上传成功，准备跳转到确认页面")
                                
                                // 关闭加载对话框
                                dismissLoadingDialog()
                                
                                // 跳转到TicketConfirmationActivity并传递数据
                                val intent = Intent(this@TicketListActivity, TicketConfirmationActivity::class.java)
                                intent.putExtra("websocket_data", resultObject?.toString())
                                intent.putExtra("source", "photo")
                                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                                startActivity(intent)
                                // 注意：这里不调用finish()，确保当前页面不被关闭
                            } else {
                                // 状态码不为200，记录失败信息
                                val message = jsonObject.optString("message", "上传失败")
                                Log.e("Upload", "[$requestId] 上传失败: $message, 完整响应: $responseBody")
                            }
                        } catch (e: Exception) {
                            // JSON解析失败
                            Log.e("Upload", "[$requestId] 解析响应失败: ${e.message}", e)
                        }
                    }
                }
            }
        }.start() // 启动线程
    }

    private fun setupRecyclerView() {
        linearLayoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.adapter = adapter
        
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy > 0) { // 判断是否是向上滑动
                    val visibleItemCount = linearLayoutManager.childCount
                    val totalItemCount = linearLayoutManager.itemCount
                    val firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition()

                    // 当前已加载的条目数 >= 总条目数 - 5 时，加载更多
                    if (!viewModel.isLoadMore.value!! && totalItemCount <= firstVisibleItem + visibleItemCount + 5) {
                        if (viewModel.currentPage < viewModel.totalPage) {
                            viewModel.loadMore()
                        }
                    }
                }
            }
        })
    }

    private fun setupRefresh() {
        swipeRefreshLayout.setOnRefreshListener {
            viewModel.refreshData()
        }
    }

    // 创建WebSocket处理器
    private val webSocketHandler = object : SimpleWebSocketHandler {
        override fun onMessageReceived(type: WebSocketMessageType, message: String) {
            Log.i("WebSocket-List", "收到消息: $message")
            
            // 处理收到的消息
            try {
                // 解析JSON消息
                val jsonObject = org.json.JSONObject(message)
                val business = jsonObject.getInt("business")
                val data = jsonObject.optString("data", "")

                // 检查是否是推流响应消息 {"business": 0, "data": "ok"}
                if (isTicketListVisible &&business == 0 && data == "ok") {
                    Log.i("WebSocket", "收到推流响应消息: $message，当前Activity可见，执行跳转")
                    // 跳转到StreamingActivity进行推流

                }
            } catch (e: Exception) {
                Log.e("WebSocket", "解析消息失败: ${e.message}")
            }
        }

        override fun onConnectionChanged(connected: Boolean) {
            val status = if (connected) "已连接" else "未连接"
            Toast.makeText(this@TicketListActivity, "WebSocket连接状态: $status", Toast.LENGTH_SHORT).show()
        }

        override fun onError(errorMsg: String) {
            Toast.makeText(this@TicketListActivity, "WebSocket错误: $errorMsg", Toast.LENGTH_SHORT).show()
            Log.e("WebSocket", "错误: $errorMsg")
        }
    }

    override fun onResume() {
        // 必须调用父类的onResume方法，确保基础功能正常
        super.onResume()

        // 检查是否需要刷新数据
        if (intent.getBooleanExtra(NEED_REFRESH, true)) {
            Log.d(TAG, "检测到刷新标志，执行数据刷新")
            viewModel.refreshData()
            // 清除标志，避免重复刷新
            intent.removeExtra(NEED_REFRESH)
        }
        
        /**
         * 重新注册我们自己的webSocketHandler，确保消息能被正确处理
         * 这很重要，因为我们需要处理特定的消息并跳转到StreamingActivity
         */
        WebSocketService.getInstance().registerHandler(webSocketHandler, this)
    }


    override fun onPause() {
        super.onPause()
    }
    
    override fun onDestroy() {
        // 确保在Activity销毁时关闭加载对话框
        dismissLoadingDialog()
        
        // 注销我们在onResume中注册的webSocketHandler
        WebSocketService.getInstance().unregisterHandler(webSocketHandler)
        
        // 调用父类的onDestroy方法
        super.onDestroy()
    }
}
